#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
  int car=0,f,start,stop,begin;
  unsigned int c;

  FILE *fpread;
  FILE *fpidx;

  char file[sizeof(argv[1])];

  if (argc != 3) {
    printf("USAGE = gl fichier ligne\n");
    exit(1);
  }
  strcpy(file,argv[1]); /*Copying name of file for concat */
  fpread = fopen(file,"r");
  if (fpread == NULL) {
    printf("Error openning reading file : %s\n",argv[1]);
    abort();
  }
  /* Openning idx file in read only */
  fpidx = fopen(strcat(file,".idx"),"r");
  if (fpidx == NULL) {
    printf("Error openning writing file : %s\n",file);
    abort();
  }
  
  /* Déplacement à l'emplacement correspondant à la ligne */
  car=atoi(argv[2]);
  start=car*sizeof(int); /*Calcul du décallage nécessaire */
  printf("Lecture du fichier .idx a l'octet %i\n",start);

  f=fseek(fpidx,start,SEEK_SET);
  if (f != 0) { printf("Erreur lors du fseek"); exit(1); }
  if (fread(&begin,sizeof(int),1,fpidx) != 1) { /* begin = where to find the line on main file */
    printf("Erreur lors de la lecture de l'index");
    abort();
  }
  if (fread(&stop,sizeof(int),1,fpidx) != 1) { /* stop = where to stop on the mail file */
   printf("Erreur lors de la lecture de l'index");
    abort();
  }

  printf("On commence la lecture a l'octet %i et on terminera a %i\n",begin,stop);
  f=fseek(fpread,begin,SEEK_SET);
  if (f != 0) { printf("Erreur lors du fseek"); exit(1); }

  while ((c = fgetc(fpread)) != EOF) {
     if (begin == stop) {
       /* If begin == stop, we have read the line */
       break;
     }
     if (putchar(c) == EOF) { /* Printing line */
        printf("Erreur lors de l'écriture");
        abort();
     }
     begin++; 
   }


  fclose(fpidx);
  fclose(fpread);
  return EXIT_SUCCESS;
}
